package fr.imag.wifibot.geiger;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

import fr.imag.wifibot.master.IMasterService;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class Activator implements BundleActivator, SerialPortEventListener {
	private BundleContext context;
	
	private static final boolean D = true;
	
	private IMasterService service;
	
	private SerialPort serialPort;
    /** The port we're normally going to use. */
	private static final String PORT_NAMES[] = {
			"/dev/ttyUSB0", // Linux
			};
	
	/** Milliseconds to block while waiting for port open */
	private static final int TIME_OUT = 2000;
	/** Default bits per second for COM port. */
	private static final int DATA_RATE = 9600;
	
	/** Buffered input stream from the port */
	private InputStream input;

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		this.context = context;
		System.out.println("Master dit : \"Geiger, à toi de jouer !\"");
		
		ServiceReference reference = context
				.getServiceReference(IMasterService.class.getName());
		service = (IMasterService) context.getService(reference);
		
		CommPortIdentifier portId = null;
		Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

		if(D) System.out.println("Getting ports...");
		// iterate through, looking for the port
		while (portEnum.hasMoreElements()) {
			CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
			if(D) System.out.println("# Port : " + currPortId.getName());
			
			for (String portName : PORT_NAMES) {
				if (currPortId.getName().equals(portName)) {
					portId = currPortId;
					break;
				}
			}
		}

		if (portId == null) {
			System.out.println("Could not find COM port.");
			return;
		}

		try {
			// open serial port, and use class name for the appName.
			serialPort = (SerialPort) portId.open(this.getClass().getName(),
					TIME_OUT);

			// set port parameters
			int data_rate = DATA_RATE;
			
			serialPort.setSerialPortParams(data_rate,
					SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1,
					SerialPort.PARITY_NONE);

			// open the streams
			input = serialPort.getInputStream();

			// add event listeners
			serialPort.addEventListener(this);
			serialPort.notifyOnDataAvailable(true);
		} catch (Exception e) {
			System.err.println(e.toString());
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		if (serialPort != null) {
			serialPort.removeEventListener();
			serialPort.close();
		}
		
		System.out.println("Master dit : \"Geiger revient dans ta pokeball !\"");
	}
	


	/**
	 * Handle an event on the serial port. Read the data and print it.
	 */
	public synchronized void serialEvent(SerialPortEvent oEvent) {
		if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
			try {
				int available = input.available();
				byte chunk[] = new byte[available];
				char i = (char) input.read();

				// Displayed results are codepage dependent
				String msg = new String(chunk, Charset.forName("UTF-8"));
				
				service.incomingMessage("$GEI," + i);
//				System.out.println("Plink : " + input.read());
			} catch (Exception e) {
				System.err.println(e.toString());
			}
		}
		// Ignore all the other eventTypes, but you should consider the other ones.
	}
}
